package com.erp.serviceIMP;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.danga.MemCached.MemCachedClient;
import com.erp.dao.TeamDAO;
import com.erp.entity.Team;
import com.erp.service.TeamService;

@Service("teamService")
public class TeamServiceIMP implements TeamService {

    @Autowired
    private MemCachedClient memCachedClient;
    @Autowired
    private TeamDAO teamMapper;
    
    private static final int maxCount=9999;
    
    public List<Team> findAll() {
        List<Team> list = new ArrayList<Team>();
        Team team = null;
        for(int i=0;i<maxCount;i++){
            team = (Team) memCachedClient.get(keyStrategy(i));
            if(team!=null){
                list.add(team);
            }
        }
        if(list.size()==0){
            list = teamMapper.findAll();
            for(Team te:list){
                memCachedClient.add(keyStrategy(te.getId()), te);
            }
            
        }
        return list;
    }

    public Team findById(int id) {
        Team team = (Team) memCachedClient.get(keyStrategy(id));
        if(team==null){
            team=teamMapper.findById(id);
            if(team!=null){
                memCachedClient.add(keyStrategy(team.getId()), team);
            }
        }
        return team;
    }

    public void insert(Team team) throws Exception {
        teamMapper.insert(team);
        memCachedClient.add(keyStrategy(team.getId()), team);        
    }

    public void update(Team team) throws Exception {
        teamMapper.update(team);
        memCachedClient.set(keyStrategy(team.getId()), team);
        
    }

    public void delete(int id) throws Exception {
        teamMapper.delete(id);
        memCachedClient.delete(keyStrategy(id));
    }
    
    private String keyStrategy(int id){
        return "team"+id;
    }

}
